package com.yf.callrecorder;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class RecordService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		PhoneStateListener listener = new MyPhoneStateListener();
		manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	private class MyPhoneStateListener extends PhoneStateListener {
		private MediaRecorder recorder;

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				Log.v("MyPhoneStateListener", "空闲状态");
				if (recorder != null) {
					//停止录音
					recorder.stop();
					//重置recorder,可被重用
					recorder.reset();
					//释放recorder，不可被重用
					recorder.release();
				}
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				Log.v("MyPhoneStateListener", "响铃");
				recorder = new MediaRecorder();
				// MIC只录自己的声音，VOICE_CALL记录双方通话(国外只允许录自己的声音)
				recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
				// 设置输出格式，3gp压缩比高质量差
				recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
				// 设置音频编码，AMR_NB（早期手机铃声格式，NB-narrow band窄带）低质量，AMR_WB（wide band）高质量
				recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				// 设置录音文件保存路径
				recorder.setOutputFile(getCacheDir() + "/" + incomingNumber + ".3gp");
				// 录音机准备
				try {
					recorder.prepare();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				Log.v("MyPhoneStateListener", "摘机接听");
				recorder.start();
				break;

			default:
				break;
			}
		}
	}
}
